const express = require('express');
const bodyParser = require('body-parser');
const cors = require('cors');
const helmet = require('helmet');
const session = require('express-session');
const path = require('path');
require('dotenv').config();

const eventRoutes = require('./routes/eventRoutes');
const weworkRoutes = require('./routes/weworkRoutes');
const scriptSourceRoutes = require('./routes/scriptSourceRoutes');
const { weworkAuth, checkAuth, logout } = require('./middleware/weworkAuth');

const app = express();

// 中间件
app.use(helmet({
  contentSecurityPolicy: {
    directives: {
      defaultSrc: ["'self'"],
      scriptSrc: ["'self'", "'unsafe-inline'"],
      scriptSrcAttr: ["'unsafe-inline'"],
      styleSrc: ["'self'", "'unsafe-inline'"]
    }
  }
}));
app.use(cors());
app.use(bodyParser.json());

// 会话配置
app.use(session({
  secret: process.env.SESSION_SECRET || 'default-secret-key-please-change',
  resave: false,
  saveUninitialized: false,
  cookie: {
    secure: process.env.NODE_ENV === 'production' && process.env.PROTOCOL === 'https',
    maxAge: 24 * 60 * 60 * 1000 // 24小时
  }
}));

// 静态文件服务
app.use(express.static(path.join(__dirname, 'public')));

// 认证相关路由
app.get('/logout', logout);

// 公开路由（不需要认证）- 允许游戏客户端记录事件
const eventController = require('./controllers/eventController');
app.post('/api/events/record', eventController.recordEvent);

// 需要认证的API路由
app.use('/api/events', weworkAuth, eventRoutes);
app.use('/api/wework', weworkAuth, weworkRoutes);
app.use('/api/script-sources', weworkAuth, scriptSourceRoutes);

// 健康检查
app.get('/health', (req, res) => {
  res.status(200).json({ status: 'ok', time: new Date().toLocaleString('zh-CN') });
});

// 统计页面 (需要管理员权限)
app.get('/stats', weworkAuth, (req, res) => {
  res.sendFile(path.join(__dirname, 'public/stats.html'));
});

// 脚本来源管理页面 (需要管理员权限)
app.get('/sources', weworkAuth, (req, res) => {
  res.sendFile(path.join(__dirname, 'public/sources.html'));
});

// 企业微信演示页面 (需要管理员权限)
app.get('/wework-demo', weworkAuth, (req, res) => {
  res.sendFile(path.join(__dirname, 'public/wework-demo.html'));
});

// 配置Express信任代理，以便正确处理转发头
app.set('trust proxy', true);

// 获取当前协议
const getProtocol = (req) => {
  // 优先使用X-Forwarded-Proto头
  if (req.headers['x-forwarded-proto']) {
    return req.headers['x-forwarded-proto'].split(',')[0].trim();
  }
  
  // 其次使用Express的req.protocol（已配置trust proxy，会自动处理X-Forwarded-Proto）
  if (req.protocol) {
    return req.protocol;
  }
  
  // 最后使用环境变量中的协议设置
  if (process.env.PROTOCOL) {
    return process.env.PROTOCOL.toLowerCase() === 'https' ? 'https' : 'http';
  }
  
  // 默认使用HTTP
  return 'http';
};

// 获取当前主机
const getHost = (req) => {
  // 优先使用X-Forwarded-Host头
  if (req.headers['x-forwarded-host']) {
    return req.headers['x-forwarded-host'].split(',')[0].trim();
  }
  
  // 其次使用请求的host头
  return req.get('host');
};

// 生成完整URL
const getFullUrl = (req, path = '') => {
  const protocol = getProtocol(req);
  const host = getHost(req);
  return `${protocol}://${host}${path}`;
};

// 首页 (需要管理员权限)
app.get('/', weworkAuth, (req, res) => {
  const baseUrl = getFullUrl(req);
  res.send(`
    <html>
      <head>
        <title>游戏事件后端服务</title>
        <style>
          body { font-family: Arial, sans-serif; max-width: 800px; margin: 0 auto; padding: 20px; }
          h1 { color: #333; }
          .endpoint { background: #f4f4f4; padding: 10px; margin: 10px 0; border-radius: 5px; }
          code { background: #eee; padding: 2px 5px; border-radius: 3px; }
        </style>
      </head>
      <body>
        <h1>游戏事件后端服务</h1>
        <p>API 服务已成功启动！</p>
        
        <div style="margin: 20px 0; padding: 10px; background: #e9f7ef; border-radius: 5px;">
          <h3>快速链接:</h3>
          <ul>
          <li><a href="/stats">查看事件统计页面</a></li>
          <li><a href="/sources">脚本来源管理</a></li>
          <li><a href="/wework-demo">企业微信接入演示</a></li>
          </ul>
        </div>
        
        <h2>可用端点：</h2>
        <div class="endpoint">
          <h3>记录事件</h3>
          <p><code>POST /api/events/record</code></p>
          <p>请求体示例:</p>
          <pre><code>{
  "event_type": "game_start",
  "event_data": { "level": 1 },
  "user_id": "user123",
  "session_id": "sess456"
}</code></pre>
        </div>
        
        <div class="endpoint">
          <h3>获取统计数据</h3>
          <p><code>GET /api/events/stats</code></p>
          <p>可选查询参数: <code>script_source</code> - 按脚本来源筛选</p>
        </div>
        
        <div class="endpoint">
          <h3>获取脚本来源列表</h3>
          <p><code>GET /api/events/sources</code></p>
        </div>
        
        <div class="endpoint">
          <h3>企业微信数据</h3>
          <p><code>POST /api/wework/data</code></p>
          <p>可选查询参数: <code>script_source</code> - 按脚本来源筛选</p>
        </div>
        
        <div class="endpoint">
          <h3>脚本来源管理</h3>
          <p><code>GET /api/script-sources</code> - 获取所有脚本来源</p>
          <p><code>POST /api/script-sources</code> - 添加新脚本来源</p>
          <p><code>PUT /api/script-sources/:id</code> - 更新脚本来源</p>
        </div>
        
        <div class="endpoint">
          <h3>健康检查</h3>
          <p><code>GET /health</code></p>
        </div>
      </body>
    </html>
  `);
});

// 启动服务器
const PORT = process.env.SERVER_PORT || 3000;
app.listen(PORT, () => {
  console.log(`服务器运行在端口 ${PORT}`);
});